package cn.wolfcode.trip.admin.web.controller;

import cn.wolfcode.trip.admin.util.UploadUtil;
import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.domain.ProductType;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.ProductQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IProductService;
import cn.wolfcode.trip.base.service.IProductTypeService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 商品控制器
 */
@RequestMapping("/product")
@Controller
public class ProductController {
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductTypeService typeService;
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") ProductQueryObject qo, Model model) {
        model.addAttribute("result",productService.query(qo));
        List<ProductType> list = typeService.listAll();
        model.addAttribute("types",list);
        return "product/list";
    }

    @RequestMapping("/saveOrUpdate")@ResponseBody
    public Object saveOrUpdate(Product product, MultipartFile image){

        JSONResult json = new JSONResult();
        try {
            if (image != null) {
                String upload = UploadUtil.upload(image, UploadUtil.IMG_BASE_PATH + "/upload");
              product.setImg(upload);
            }
            productService.saveOrUpdate(product);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }
    @RequestMapping("/delete")@ResponseBody
    public Object saveOrUpdate(Long id){

        JSONResult json = new JSONResult();
        try {
            productService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }
}
